package socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import service.ServerAction;


public class ChatServer {
	// [V] There we save connections of all sockets with server
	public static List<Connection> connections = new ArrayList<Connection>();
	
	public void startServer() throws ClassNotFoundException, IOException {
		ServerSocket providerSocket = null;
		Socket connection = null;
		ObjectOutputStream out;
		ObjectInputStream in;
		boolean listening = true;
		
		try {
			providerSocket = new ServerSocket(2003);
		} catch (IOException e){
			System.err.println("Could not listen on port: 2003.");
		}
			
		while(listening){
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			
			out = new ObjectOutputStream(connection.getOutputStream());
			in = new ObjectInputStream(connection.getInputStream());
			
			ServerAction serverAction = new ServerAction(out, in);
			
			if (serverAction.authentication()){
				new ChatServerClientThread(connection, out, in).start();
			}
		}
		
		providerSocket.close();
	}
	
}
